<template>
  <div class="page-view">
    <div class="map-view">
      <MyMap @ready="ready">
        <MapGeo v-if="layers" :json="layers" :stroke="{ color: '#f0f', width: 2 }"></MapGeo>
        <MapQuery></MapQuery>
        <MapLegend ref="legendRef"></MapLegend>
      </MyMap>
    </div>
    <div class="select-filds">
      <a-form :labelCol="{ span: 5 }" :wrapperCol="{ span: 19 }">
        <a-form-item label="区域">
          <a-tree-select
            v-model="searchForm.xzqdm"
            :treeData="city"
            :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }"
            :replaceFields="{
              value: 'dicCode',
              label: 'dicValue'
            }"
            placeholder="请选择区域"
            style="width: 100%"
          >
          </a-tree-select>
        </a-form-item>
        <a-form-item label="要素">
          <a-select v-model="searchForm.classify" style="width: 100%;">
            <a-select-option value="point">调查样点</a-select-option>
            <a-select-option value="shape">土地利用</a-select-option>
            <a-select-option value="xb">林地小班</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="类型">
          <a-select v-model="searchForm.quota" style="width: 100%;">
            <a-select-option value="fl">土壤肥力等级评价</a-select-option>
            <a-select-option value="qjd">土壤清洁度等级评价</a-select-option>
          </a-select>
        </a-form-item>
        <div style="text-align: center">
          <a-button type="primary" @click="handleClick"> 统计分析 </a-button>
        </div>
      </a-form>
    </div>

    <div class="result-icon">
      <div class="icon-item"><a-icon type="table" :class="{ 'active': showTable}" @click="showTable = !showTable" /></div>
    </div>

    <div class="loading-warp" v-if="showLoading">
      <div class="loading-out">
        <Loading></Loading>
        <div class="text">分析中</div>
      </div>
    </div>

    <a-drawer
      placement="bottom"
      :visible="showTable"
      :mask="false"
      @close="showTable = !showTable"
      :height="360"
      :bodyStyle="{ padding: '8px 8px 0px 8px' }"
    >
      <div slot="title" style="display: flex; justify-content: space-between">
        <div>统计结果</div>
        <div style="margin-right: 40px">
          <a-button type="link" size="small" icon="download" @click="exportExcel">导出</a-button>
        </div>
      </div>
      <a-table
        rowKey="properties.id"
        :dataSource="valueData"
        size="small"
        :bordered="false"
        :columns="columns"
        :pagination="pagination"
      >
      </a-table>
    </a-drawer>
  </div>
</template>

<script>
import { MyMap, MapGeo, MapMarker, MapLegend, MapQuery } from '@/map'
import { queryAllcity, queryCityGeo } from '@/api/common'
import MapTree from '@/views/home/components/tree'
import EchartsBox from './components/chart.vue'
import Loading from '@/components/loading'
import { QueryBySQLParameters, QueryService } from '@supermap/iclient-ol'
import { export_array_to_excel as exportArrayToExcel } from '@/utils/excel'

export default {
  name: 'Inference',
  components: {
    MyMap,
    MapMarker,
    MapGeo,
    MapQuery,
    MapTree,
    MapLegend,
    Loading,
    EchartsBox
  },
  data () {
    return {
      showTable: false,
      showLoading: false,
      searchForm: {
        xzqdm: '110117',
        classify: 'point',
        quota: 'fl'
      },
      city: [],
      layers: undefined,
      pagination: {
        pageSize: 5
      },
      columns: [
        {
          title: '类别',
          dataIndex: 'properties.type',
          key: 'type'
        },
        {
          title: '面积',
          dataIndex: 'properties.total',
          key: 'total',
          customRender: (text) => Number(text).toFixed(3)
        },
        {
          title: '等级',
          dataIndex: 'properties.grade',
          key: 'grade'
        }
      ],
      valueData: []
    }
  },
  created () {
    this.fetchCity()
    this.handleClick()
  },
  methods: {
    ready (map) {
      // 创建MVT图层
      // const vectorTileLayer = new VectorTileLayer({
      //   source: new VectorTileSource({
      //     url: window.mapService + '/iserver/services/map-LYSP/rest/maps/地类图斑@业务数据',
      //     format: new MVT(),
      //     projection: 'EPSG:4326'
      //   })
      // })
      // map.addLayer(vectorTileLayer)
    },
    async fetchCity () {
      try {
        const { data } = await queryAllcity()
        this.city = data[0].children
      } catch (err) {
        throw err
      }
    },
    handleChange () {
      this.layers = undefined
      if (this.searchForm.xzqdm) {
        queryCityGeo({
          xzqdm: this.searchForm.xzqdm
        }).then((res) => {
          this.layers = JSON.parse(res.data)
        })
      }
    },
    handleClick () {
      this.dataMarker = undefined
      this.handleChange()
      if (this.searchForm.classify === 'point') {
        // 样点统计
        this.xzq()
      } else if (this.searchForm.classify === 'shape') {
        this.riskData()
      } else if (this.searchForm.classify === 'xb') {
        this.evaluateResult()
      }
    },
    /**
     * 样点统计
     */
    async xzq () {
      this.showLoading = true
      let quota = 'fl'
      switch (this.searchForm.quota) {
        case 'fl':
          quota = '肥力等'
          break
        case 'qjd':
          quota = 'POLLUTION'
          break
      }
      const url = window.service.mapService + '/iserver/services/map-LYSP/rest/maps/平谷园林草地样点评价@业务数据'
      const name = '平谷园林草地样点评价@业务数据3'
      const attributeFilter = `ZLDWDM like '${this.searchForm.xzqdm}%'`
      const fields = [ 'SUBSTR(TDLYLX, 1, 2) AS type', 'COUNT(*) as total', `${quota} as grade` ]

      const groupBy = `type,${quota}`
      try {
        const { result } = await this.query(url, { name, attributeFilter, groupBy, fields })
        if (result.totalCount) {
          this.valueData = result.recordsets[0].features.features
          this.showTable = true
        }
      } catch (err) {
        this.$message.error(err || '查询失败')
      }
      this.showLoading = false
    },
    /**
     * 小班统计
     */
    async evaluateResult () {
      this.showLoading = true
      let quota = 'fl'
      switch (this.searchForm.quota) {
        case 'fl':
          quota = '等级'
          break
        case 'qjd':
          quota = 'POLLUTION'
          break
      }
      let code = ''
      if (this.searchForm.xzqdm.length === 6) {
        // 截取后两位
        code = `COUNTY_ID='${this.searchForm.xzqdm.slice(-2)}'`
      } else if (this.searchForm.xzqdm.length === 9) {
        // 截取后四位
        code = `TOWN_ID='${this.searchForm.xzqdm.slice(-4)}'`
      } else if (this.searchForm.xzqdm.length === 12) {
        // 截取后六位
        code = `VILLAGE_ID='${this.searchForm.xzqdm.slice(-6)}'`
      }
      const url = window.service.mapService + '/iserver/services/map-LYSP/rest/maps/林地小班@业务数据'
      const name = '平谷林地小班评价_1_1@业务数据3#1'
      // SmID<10
      const attributeFilter = code
      const fields = ['地类 AS type', `sum(面积（) AS total`, `${quota} as grade`]
      // TODO 修改分类字段
      const groupBy = `地类,${quota}`
      try {
        const { result } = await this.query(url, { name, attributeFilter, groupBy, fields })
        if (result.totalCount) {
          this.valueData = result.recordsets[0].features.features
          this.showTable = true
        }
      } catch (err) {
        this.$message.error(err || '查询失败')
      }
      this.showLoading = false
    },
    /**
     * 土地利用统计
     */
    async riskData () {
      this.showLoading = true
      let quota = 'fl'
      switch (this.searchForm.quota) {
        case 'fl':
          quota = '等级'
          break
        case 'qjd':
          quota = 'POLLUTION'
          break
      }
      const url = window.service.mapService + '/iserver/services/map-LYSP/rest/maps/地类图斑@业务数据'
      const name = '平谷园林草地地块评价@业务数据3.1'
      const attributeFilter = `ZLDWDM like '${this.searchForm.xzqdm}%'`
      const fields = [`SUBSTR(DLBM,1,2) AS type`, `SUM(TBMJ) AS total`, `${quota} as grade`]
      const groupBy = `SUBSTR(DLBM,1,2),${quota}`
      try {
        const { result } = await this.query(url, { name, attributeFilter, groupBy, fields })
        if (result.totalCount) {
          this.valueData = result.recordsets[0].features.features
          this.showTable = true
        }
        this.showLoading = false
      } catch (err) {
        this.showLoading = false
        this.$message.error(err || '查询失败')
      }
    },
    // 查询
    query (url, option) {
      return new Promise(async (resolve, reject) => {
        try {
          const queryParam = new QueryBySQLParameters({
            queryParams: option,
            startRecord: 0
          })
          // 发送查询请求
          const queryService = new QueryService(url)
          const result = await queryService.queryBySQL(queryParam)
          resolve(result)
        } catch (err) {
          reject(err)
        }
      })
    },
    // 格式化返回值
    formatTableData (data) {
      // const type = {
      //   '02': '园地',
      //   '03': '林地',
      //   '04': '草地'
      // }
      // const grade = []
      // let group = {}
      // const totleNumber = 0
      // data.forEach(item => {
      //   const type = item.type
      //   if (group[type]) {
      //     group{type}[item.grade] = item.grade
      //   }
      // })
    },
    // 导出excel
    exportExcel () {
      if (!this.valueData.length) {
        this.$message.error('无导出数据')
        return false
      }
      exportArrayToExcel({
        sheet: [
          {
            columns: this.columns,
            data: this.valueData,
            sheetName: this.searchForm.xzqdm
          }
        ],
        filename: '分析结果'
      })
      exportArrayToExcel({
        sheet: [
          {
            columns: this.columns,
            data: this.valueData2,
            sheetName: this.searchForm.xzqdm
          }
        ],
        filename: '分析结果'
      })
    }
  }
}
</script>

<style lang="less" scoped>
.page-view {
  position: relative;
  height: 100%;
  .map-view {
    position: absolute;
    top: -24px;
    right: -24px;
    bottom: -24px;
    left: -24px;
  }
}
.select-filds {
  position: absolute;
  top: 0;
  right: 0;
  padding: 24px;
  width: 360px;
  border-radius: 4px;
  background: #ffffff;
  box-shadow: 0 -1px 2px rgba(0, 0, 0, 0.03);
}
.group {
  font-size: 16px;
}
.left-tree {
  position: absolute;
  top: 0;
  left: 0;
  z-index: 9;
  height: 100%;
  background: #ffffff;
  .tree-content {
    width: 300px;
    .header {
      position: relative;
      padding: 0 14px;
      height: 40px;
      font-size: 16px;
      color: #222222;
      background: #ebeef5;
      line-height: 40px;
    }
  }
  .close {
    position: absolute;
    top: 50%;
    right: -20px;
    width: 20px;
    height: 100px;
    border: 1px solid rgba(0, 0, 0, 0.1);
    border-left: none;
    border-radius: 0 2px 2px 0;
    line-height: 100px;
    transform: translateY(-50%);
    cursor: pointer;
    background: #ebeef5;
  }
}
.loading-warp {
  position: absolute;
  top: 0;
  right: 0;
  bottom: 0;
  left: 0;
  display: flex;
  justify-content: center;
  align-items: center;
  background: rgba(0, 0, 0, 0.03);
  .loading-out {
    display: inline-block;
    padding: 16px 24px;
    border-radius: 4px;
    background: rgba(0, 0, 0, 0.5);
  }
  .text {
    text-align: center;
    color: #ffffff;
  }
}
.reslut-filds {
  position: absolute;
  top: 20px;
  left: 320px;
  z-index: 2;
  width: 360px;
  height: 300px;
  background: #ffffff;
}
.page-legend {
  position: absolute;
  right: 24px;
  bottom: 34px;
  z-index: 2;
  background: #ffffff;
}
.result-icon {
  position: absolute;
  top: 40%;
  right: 0;
  .icon-item {
    margin: 8px 0;
    padding: 4px 8px;
    font-size: 20px;
    font-weight: bold;
    border-radius: 4px;
    background: #ffffff;
  }
  .active {
    color: @primary-color;
  }
}
</style>
